<template>
    <div>
        <div>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="网站设置" name="first">
                <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="120px"
                    class="demo-ruleForm"
                    :size="formSize"
                    status-icon
                >
                    <el-form-item label="网站名称" prop="sitename">
                        <el-input v-model="ruleForm.sitename" />
                    </el-form-item>
                    <el-form-item label="网站url" prop="url">
                        <el-input v-model="ruleForm.url" />
                    </el-form-item>
                    <el-form-item label="关键字" prop="keywords">
                        <el-input v-model="ruleForm.keywords" />
                    </el-form-item>
                    <el-form-item label="简介" prop="desc">
                        <el-input v-model="ruleForm.desc" />
                    </el-form-item>
                    <el-form-item label="版权" prop="copyright">
                        <el-input v-model="ruleForm.copyright" />
                    </el-form-item>
                    <el-form-item label="小程序ID" prop="appid">
                        <el-input v-model="ruleForm.appid" />
                    </el-form-item>
                    <el-form-item label="小程序密钥" prop="appsecret">
                        <el-input v-model="ruleForm.appsecret" />
                    </el-form-item>
                    <el-form-item label="公众号ID" prop="miniappid">
                        <el-input v-model="ruleForm.miniappid" />
                    </el-form-item>
                    <el-form-item label="公众号密钥" prop="minisecret">
                        <el-input v-model="ruleForm.minisecret" />
                    </el-form-item>
                </el-form>
                <el-upload  style="margin-left:100px" class="avatar-uploader"
                    action="http://visit.lening365.com/visit/api/upload"
                    :headers={Authorization:token}
                    method="post"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-button type="primary" @click="submitForm(ruleFormRef)" style="margin-left:100px;margin-top: 40px;">
                    提交
                </el-button>
            </el-tab-pane>
            <el-tab-pane label="离校二维码" name="second" style="width: 20%;margin:  10% auto; height: 80%;">
              <vue-qr
                ref="qrcode"
                :text="qrCodeValue"
                logo-src=""
                :size="500"
                style="display: none"
              ></vue-qr>
              <img src="../../assets/image/bac.jpg"  style=" width: 100%;">
              <div style="  width: 100%;text-align: center;margin-top: 10px; color: rgb(66, 185, 131);cursor: pointer;" @click="download">下载二维码</div>
            </el-tab-pane>
            <el-tab-pane label="Form表单设置" name="third">
              <el-button type="success" style="margin:20px;" size="small" @click="add" v-show="isshow">添加</el-button>
              <el-button type="primary" style="margin:20px;" size="small" plain @click="info" v-show="!isshow">返回</el-button>
              <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                label-width="120px"
                class="demo-ruleForm"
                :size="formSize"
                status-icon
                v-show="!isshow"
              >
                <el-form-item label="Form表单名" prop="name">
                  <el-input v-model="ruleForm.name" />
                </el-form-item>
                <el-form-item label="是否开启" >
                  <el-switch v-model="ruleForm.delivery" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"  :active-value="1" :inactive-value="0"/>
                </el-form-item>
                <el-button @click="resetForm(ruleFormRef)" style="margin-left: 30px; ">重置</el-button>
                <el-button type="primary" @click="qdadd(ruleFormRef)">
                  确定
                </el-button>
              </el-form>
              <el-table v-show="isshow" :data="tableData.list" border style="margin-left: 20px ;width: 100%" class="table" :cell-style="{ textAlign: 'center' }" :header-cell-style="{ 'text-align': 'center' }">
                <el-table-column type="selection" width="55" />
                <el-table-column  prop="fieldname" label="核销人姓名" />
                <el-table-column prop="is_null" label="是否启用" >
                  <template #default="scope">
                    <el-switch  v-model="scope.row.is_null" class="mb-2" active-color="#13ce66"
                      :active-value="1" :inactive-value="0" inactive-color="#ccc" @change="changeswitch(scope.row)" />
                  </template>
                </el-table-column>
                <el-table-column  label="操作" >
                  <template #default="scope">                                              
                    <el-button type="primary" size="small" @click="modification(scope)">修改</el-button>
                    <el-button type="danger" size="small" @click="deleted(scope)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
        </el-tabs>

        </div>
    </div>
</template>

<script setup lang="ts">
import { ref,reactive,onMounted } from 'vue'
import type { TabsPaneContext,FormInstance, FormRules } from 'element-plus'
import { ElMessage,ElMessageBox  } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http from "../../api/setting"
import type { UploadProps } from 'element-plus'
import { id } from 'element-plus/es/locale'
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
const qrcode = ref<typeof vueQr>(); // 实例
const qrCodeValue = ref('');
// 下载
const download = () =>{
   // TODO 接口返回数据  
      let res = "112233"
   // 数据返回生产二维码
     qrCodeValue.value = res ;
 
     // 生成二维码是属于异步行为，所以下载二维码也为异步行为
 
      const timer = setTimeout(() => {
 
       // 可打印获取二维码插件里的数据
        console.log('data', qrcode.value);
        console.log('下载签到码', qrcode.value.imgUrl);
 
        // 下载
        // 注，当在vue3+ts项目中，识别不了document是，前面加上window
 
        const eleLink = window.document.createElement('a');
        eleLink.style.display = 'none';
        eleLink.download = '二维码';
        eleLink.href = qrcode.value.imgUrl;
        eleLink.click();
        eleLink.remove();
        clearTimeout(timer);
      });
}
let token=JSON.parse(JSON.stringify(sessionStorage.getItem("token")))
const imageUrl = ref('')
const isshow=ref(true)
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}


const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm:any = reactive({
    name:"",
    id:0,
    delivery:1,
    sitename: '乐柠',
    url:"http://www.jgy1985.cn",
    keywords:"品学兼修，开物成务",
    desc:"北京科技经营管理学是经教育部批准的的全日制普通高等职业院校。学校前身是1985年5月创办的中国科技经营管理大学;2001年4月5日更名为北京科技经营管理学院。",
    copyright:"北京科技经营管理学院",
    appid:"wxad7528a252dd680a",
    appsecret:"00257f3127812eb81e0a3ec036e9efg",
    miniappid:"22222",
    minisecret:"s"
})
const tableData:any = reactive({
  list:[]
})
const getlist=async()=>{
  let res=await http.field()
  console.log(res)
  tableData.list=res.data
}
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入Form表单名称', trigger: 'blur' }],
    sitename: [{ required: true, message: '请输入网站名称', trigger: 'blur' }],
    url: [{ required: true, message: '请输入网站url', trigger: 'blur' }],
    keywords: [{ required: true, message: '请输入关键字', trigger: 'blur' }],
    desc: [{ required: true, message: '请输入简介', trigger: 'blur' }],
    copyright: [{ required: true, message: '请输入版权', trigger: 'blur' }],
    appid: [{ required: true, message: '请输入小程序ID', trigger: 'blur' }],
    appsecret: [{ required: true, message: '请输入小程序秘钥', trigger: 'blur' }],
    miniappid:[{ required: true, message: '请输入公众号ID', trigger: 'blur' }],
    minisecret:[{ required: true, message: '请输入公众号秘钥', trigger: 'blur' }],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
        let res:any=await http.count(ruleForm.sitename,ruleForm.url,ruleForm.keywords,ruleForm.desc,ruleForm.copyright,ruleForm.appid,ruleForm.appsecret,ruleForm.miniappid,ruleForm.minisecret)
       if(res.code==10000){
        console.log(res)
        ElMessage({
            message: res.message,
            type: 'success',
        })
       }else{
            ElMessage({
            message: res.message,
            type: 'error',
        })
        }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
onMounted(() => {
  getlist()
})
  const info=()=>{
    isshow.value=!isshow.value
  }
  const add=(scope:any)=>{
    isshow.value=!isshow.value
  }
  const modification=(scope:any)=>{
    isshow.value=!isshow.value
      ruleForm.name=scope.row.fieldname
      ruleForm.id=scope.row.id
      ruleForm.delivery=scope.row.is_null
  }
  const qdadd = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      if(ruleForm.id==0){
        let res:any=await http.adddata(ruleForm.name,0,ruleForm.delivery)
        if(res.code==10000){
        isshow.value=!isshow.value
        ruleForm.name=""
        ruleForm.id=0
        ruleForm.delivery=1
        getlist()
        ElMessage({
            message: res.message,
            type: 'success',
        })
       }else{
            ElMessage({
            message: res.message,
            type: 'error',
        })
        }
      }else{
        let res:any=await http.adddata(ruleForm.name,ruleForm.id,ruleForm.delivery)
        if(res.code==10000){
        isshow.value=!isshow.value
        ruleForm.name=""
        ruleForm.id=0
        ruleForm.delivery=1
        getlist()
        ElMessage({
            message: res.message,
            type: 'success',
        })
       }else{
            ElMessage({
            message: res.message,
            type: 'error',
        })
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
 const changeswitch=async (value:any)=>{
  let res:any=await http.adddata(value.fieldname,value.id,value.is_null)
        if(res.code==10000){
        getlist()
        ElMessage({
            message: res.message,
            type: 'success',
        })
       }else{
            ElMessage({
            message: res.message,
            type: 'error',
        })
        }
}
const deleted=async (value:any)=>{
  console.log(value.row.id)
  ElMessageBox.confirm(
    '此操作将删除该条地址信息, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      let res:any=await http.dele(value.row.id)
      if(res.code==10000){
        getlist()
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

</script>

<style scoped>

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.el-input{
    width: 350px;
}


.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
  
</style>